package network

import (
	"gitee.com/amoyx/cloud-provider/pkg/cloud/huawei/models"
	vpcv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model"
	regionv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/region"
	"strings"
)

type VpcGreeter interface {
	VPC(region string) VpcInterface
}

type VpcInterface interface {
	CreateVpc(args models.VpcRequest) (vpcId string, err error)
	DescribeVpc(id string) (result models.VpcResponse, err error)
	ListAllVpc() (list []models.VpcResponse, err error)
	DeleteVpc(id string) (err error)
}

type vpc struct {
	network *Network
	region  string
	client  *vpcv2.VpcClient
}

func newVpc(network *Network, region string) VpcInterface {
	v := &vpc{
		network: network,
		region:  region,
	}
	_client := vpcv2.NewVpcClient(
		vpcv2.VpcClientBuilder().
			WithRegion(regionv2.ValueOf(region)).
			WithCredential(network.credentials).
			Build())
	v.client = _client
	return v
}

func (v *vpc) CreateVpc(args models.VpcRequest) (vpcId string, err error) {
	request := &model.CreateVpcRequest{}
	body := &model.CreateVpcOption{
		Cidr:        &args.Cidr,
		Name:        &args.Name,
		Description: &args.Description,
	}
	request.Body = &model.CreateVpcRequestBody{
		Vpc: body,
	}
	response, err := v.client.CreateVpc(request)
	if err != nil {
		return
	}
	vpcId = response.Vpc.Id
	return
}

func (v *vpc) DescribeVpc(id string) (result models.VpcResponse, err error) {
	list, err := v.query(id)
	if len(list) > 0 {
		result = list[0]
	}
	return
}

func (v *vpc) DeleteVpc(vpcId string) error {
	request := &model.DeleteVpcRequest{}
	request.VpcId = vpcId
	_, err := v.client.DeleteVpc(request)
	return err
}

func (v *vpc) ListAllVpc() (list []models.VpcResponse, err error) {
	return v.query("")
}

func (v *vpc) query(id string) (list []models.VpcResponse, err error) {
	request := &model.ListVpcsRequest{}
	if strings.TrimSpace(id) != "" {
		request.Id = &id
	}
	response, err := v.client.ListVpcs(request)
	if err != nil {
		return
	}
	for _, row := range *response.Vpcs {
		list = append(list, models.VpcResponse{
			Cidr:        row.Cidr,
			Description: row.Description,
			Status:      row.Status.Value(),
			CreatedAt:   *row.CreatedAt,
			UpdatedAt:   *row.UpdatedAt,
			Id:          row.Id,
			Name:        row.Name,
		})
	}
	return
}
